package com.sihai.ehr.service.impl;

import com.sihai.core.*;
import com.sihai.ehr.model.biz.*;
import com.sihai.ehr.model.sys.AuditStatus;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.model.sys.OrganizationAuditing;
import com.sihai.ehr.repository.AuditingRepository;
import com.sihai.ehr.service.AuditBaseService;
import com.sihai.ehr.service.ExamQualItemSetService;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author wxn
 * @since 12-10-15 21:31
 */
@Service("examQualItemSetService")
public class ExamQualItemSetServiceImpl implements ExamQualItemSetService {
    @Resource
    private DataAccessor dataAccessor;

    @Override
    public LimitedList<ExamQualItemSet> findByTopOrganization(Long organizationId, Limit limit, Sorter sorter) {
        return dataAccessor.findByHql(ExamQualItemSet.class, "from ExamQualItemSet e where e.organization.id = ?", new Object[]{organizationId}, limit, sorter);
    }

    @Override
    public ExamQualItemSet get(Long id) {
        if(id == null){
            return null;
        }
        return dataAccessor.get(ExamQualItemSet.class, id);
    }

    @Override
    public void save(ExamQualItemSet examQualItemSet) {
        if(examQualItemSet != null){
            dataAccessor.save(examQualItemSet);
        }
    }

    @Override
    public void remove(final String ids) {
        dataAccessor.batchUpdate(new QueryCreator() {
            @Override
            public Query createQuery(Session session) {
                return session.createQuery(String.format("delete ExamQualItemSet s where s.id in (%s)", ids));
            }
        });
    }

    @Override
    public Double findPercentage(final Long organizationId) {
        //得到待删除的考核项目总比例     exam_quan_item_set
        Double itemPercentageSum = dataAccessor.findUnique(Double.class,new QueryCreator(){
            @Override
            public Query createQuery(Session session) {
                Query query = session.createQuery("select sum(e.percentage) from ExamQualItemSet e where e.organization.id = :organizationId");
                query.setParameter("organizationId", organizationId);
                return query;
            }
        });
        return itemPercentageSum;
    }
}
